package com.joven.shelltest.service.impl;

import com.joven.shelltest.common.exception.BadRequestException;
import com.joven.shelltest.service.TokenService;
import com.joven.shelltest.utils.RedisUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * @Author wzj
 * @Date 2023-07-27 08:37
 **/
@Service
public class TokenServiceImpl implements TokenService {

    @Autowired
    private RedisUtils redisUtils;

    private static final String TOKEN_PREFIX = "joven_";
    private static final String TOKEN_NAME = "token";

    @Override
    public String createToken() {
        UUID uuid = UUID.randomUUID();
        String str = uuid.toString().replaceAll("-", "");
        StringBuilder token = new StringBuilder();
        try {
            token.append(TOKEN_PREFIX).append(str);
            redisUtils.set(token.toString(), token.toString(), 50L);
            boolean notEmpty = StringUtils.isNotEmpty(token.toString());
            if (notEmpty) {
                return token.toString();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    @Override
    public boolean checkToken(HttpServletRequest request) throws Exception {
        String token = request.getHeader(TOKEN_NAME);
        // header中不存在token
        if (StringUtils.isBlank(token)) {
            token = request.getParameter(TOKEN_NAME);
            // parameter中也不存在token
            if (StringUtils.isBlank(token)) {
                throw new BadRequestException(HttpStatus.NO_CONTENT, "token不存在");
            }
        }

        long time = redisUtils.getExpire(token);
        if (time > 0) {
            throw new BadRequestException(HttpStatus.BAD_REQUEST, "请勿重复提交");
        }
//        if (!redisUtils.exists(token)) {
//            throw new BadRequestException(HttpStatus.BAD_REQUEST, "token已存在");
//        }

//        boolean remove = redisUtils.remove(token);
//        if (!remove) {
//            throw new BadRequestException(HttpStatus.BAD_REQUEST, "token已删除");
//        }
        return true;
    }

    @Override
    public boolean checkToken(String methodName, long expireTime) throws Exception {
        if(!redisUtils.exists(methodName)){
            redisUtils.set(methodName, methodName, expireTime);
            return true;
        }
        return false;
    }
}
